<script setup lang="ts">
import { ref } from 'vue'
import { onReady } from '@dcloudio/uni-app'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()

const form = ref({
	mobile: "13730708090",
	password: "8090"
})
const toast = ref()
const formRef = ref()
const rules = {
	"mobile": [
		{
			required: true, 
			trigger: ['change','blur'],
			pattern: /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
			transform(value: any) {
				return String(value);
			},
			message: '请输入正确的手机号'
		}
	],
	"password": {
		required: true,
		message: '请输入密码',
		trigger: ['change','blur']
	},
}

function submit() {
	formRef.value.validate().then(res => {
		// @ts-expect-error
		uni.$u.toast('校验通过')
		login(form.value)
	})
}

onReady(() =>{
	formRef.value.setRules(rules)
})

function login(data){
  uni.showLoading({
    title: '登录中，请稍后'
  })
  uni.login({
    provider: 'weixin', // 登录服务提供商
    onlyAuthorize: true, // 微信登录仅请求授权认证,主要是取code的值传给后端拿token
    success: (res: any) => {
      userStore
        .userLoginAction({
			code: res.code,
			...data
		})
        .then(async (e) => {
			console.log(e);
          if (userStore.token) {
            try {
              await userStore.getUserInfoAction()
			  uni.showToast({
			  	title: '登录成功',
			  	duration: 1000
			  });
              // checkStatus()
            } catch (error) {
              // 请求异常，则跳转到登录页
              userStore?.setToken('')
            }
          }
        })
        .catch((e) => {
			toast.value.show({
						type: 'error',
						message: "账号不存在，或密码错误",
					})
        })
        .finally(() => {
          uni.hideLoading()
        })
    }
  })
}
</script>

<template>
  <view class="viewport">
    <text style="font-size: 50rpx; margin: 20px 0;">欢迎登录托运人</text>
	<u--form :model="form" ref="formRef" :rules="rules">
		<u-form-item prop="mobile" label="手机号" labelWidth="60">
			<u--input border="bottom" v-model="form.mobile" placeholder="请输入手机号"/>
		</u-form-item>
		<u-form-item prop="password" label="密&nbsp;&nbsp;&nbsp;码" labelWidth="60">
			<u--input v-model="form.password" border="bottom" type="password" placeholder="请输入密码"/>
		</u-form-item>
	</u--form>
	<u-button type="primary" text="登录" @click="submit" :customStyle="{width: '50%', 'margin-top': '20px'}"/>
    <view class="tips">登录即视为你同意《服务条款》和《隐私协议》</view>
  </view>
  <u-toast ref="toast"/>
</template>
<style>
.u-btn-width{
	width: 80%;
}
.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20rpx 40rpx;
}
.tips {
  margin-top: 50rpx;
  font-size: 22rpx;
  color: #999;
  text-align: center;
}
</style>